package com.joyoung.sweep.utils.Net;

import android.util.Log;


import com.joyoung.sweep.BuildConfig;
import com.joyoung.sweep.config.Cons;
import com.joyoung.sweep.model.RmsJoyoungApi;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;



/**
 * Created by Administrator on 2017\7\17 0017.
 */

public class RetrofitSingleton {

    private volatile static RetrofitSingleton INSTANCE = null;
    private OkHttpClient okHttpClient;
    private static final int TIMEOUT_READ = 25;
    private static final int TIMEOUT_CONNECTION = 25;
    private Retrofit rmsRetrofit;

    private RetrofitSingleton() {
        if (rmsRetrofit == null) {
            rmsRetrofit = new Retrofit.Builder()
                    .baseUrl(Cons.RMS_URL)
                    .client(initClient())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        }

    }

    public synchronized static RetrofitSingleton getINSTANCE() {
        if (INSTANCE == null) {
            synchronized (RetrofitSingleton.class) {
                if (INSTANCE == null) {
                    INSTANCE = new RetrofitSingleton();
                }
            }
        }
        return INSTANCE;
    }

    private synchronized OkHttpClient initClient() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> {
            if (BuildConfig.DEBUG) { //debug安装下打印完整Body,release安装不打印
                Log.e("HttpLogInfo", message);
            }
        });
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        if (okHttpClient == null) {
            okHttpClient = new OkHttpClient.Builder()
                    .addNetworkInterceptor(logging)
                    .addInterceptor(new AppInterceptor())
                    .retryOnConnectionFailure(true)
                    .readTimeout(TIMEOUT_READ, TimeUnit.SECONDS)
                    .connectTimeout(TIMEOUT_CONNECTION, TimeUnit.SECONDS)
                    .build();
        }

        return okHttpClient;
    }


    public RmsJoyoungApi getRmsJoyoungApi() {
        return rmsRetrofit.create(RmsJoyoungApi.class);
    }
}
